import { Service } from "egg";
import { Op } from "sequelize";
import { BannerPortalDefination } from "../../template/portal/BannerPortalDefination";
import { EntryPortalDefination } from "../../template/portal/EntryPortalDefination";
import { LabelPortalDefination } from "../../template/portal/LabelPortalDefination";
import { NoticePortalDefination } from "../../template/portal/NoticePortalDefination";
import { ShopListPortalDefination } from "../../template/portal/ShopListPortalDefination";
import { deleteNullOrUndefinedField, getCurrentStimp } from "../../utils";

export default class TemplateService extends Service {

  /**
   * 预置接口
   */
  async preset() {
    // 准备套件
    // banner
    const banner = new BannerPortalDefination()
    const notice = new NoticePortalDefination()
    const label = new LabelPortalDefination()
    const entry = new EntryPortalDefination()
    const shop = new ShopListPortalDefination()
    const shop2 = new ShopListPortalDefination()
    const shop3 = new ShopListPortalDefination()
    const shop4 = new ShopListPortalDefination()
    // const shop = new ShopListPortalDefination()

    shop2.title = '推荐套餐'
    shop3.title = '本店特色'
    shop4.title = '热门菜品'



    const items = [
      banner,
      notice,
      label,
      entry,
      shop,
      shop2,
      shop3,
      shop4
    ]
    const stemp = getCurrentStimp();

    for (const it of items) {
      await this.ctx.model.PortalDef.create({
        title: it.title,
        create_at: stemp,
        update_at: stemp,
        page_id: 1,
        type: it.schema.name,
        properties: JSON.stringify(it.schema),
        shop_id: 1
      })
    }
  }

  async list(page = 1, pageSize = 10) {
    const queryParams = {
      // where: deleteNullOrUndefinedField(query),
      offset: (Number(page) - 1) * pageSize,
      limit: pageSize,
      distinct: true,

      order: [['id', 'DESC']],
    };

    const result = await this.ctx.model.TemplateDef.findAndCountAll(queryParams);

    return {
      list: result.rows,
      total: result?.count || 0,
      page,
      pageSize,
    }
  }

  /**
   * 根据
   * @param tplId 
   * @param pageId 
   */
  async detail(tplId: number, pageId: number, status = '', version?: number) {

    const templateReq = this.ctx.model.TemplateDef.findOne({
      where: {
        id: tplId,
        'is_delete': 0
      },
      raw: true
    })

    const pageReq = this.ctx.model.PageDef.findOne({
      where: {
        id: pageId,
        'is_delete': 0
      },
      raw: true
    })

    const portalsReq = this.ctx.model.PortalDef.findAll({
      where: {
        page_id: pageId,
        'is_delete': 0
      },
      order: [['sort_id', 'ASC']],
      raw: true
    })

    const [template, page, portals] = await Promise.all([templateReq, pageReq, portalsReq])


    const portalValue = {}
    const selectIds: number[] = []
    for (const p of portals) {
      const ps = {
        templateId: tplId,
        pageId: pageId,
      }
      if (status) {
        ps['status'] = status
      }
      if (version !== undefined) {
        ps['vId'] = version
      }
      const data = await this.ctx.model.AppUserPage.findOne({
        where: {
          ...ps,
          portalId: p.id
        },
        order: [['id', 'DESC']],
        raw: true
      })
      if (data) {

        let pps = data.properties
        if (pps) {
          pps = JSON.parse(pps)
        }

        if (data.enabled === 1) {
          selectIds.push(p.id)
        }

        if (pps?.type && this.ctx.model[pps?.type]) {
          const strcutData = await this.ctx.model[pps.type].findAll({
            where: {
              id: {
                [Op.in]: pps.value
              }
            }
          })
          if (data.enabled === 1) {
            portalValue[p.type] = {
              ...pps,
              strcutData
            }
          }
        } else {
          if (data.enabled === 1) {
            portalValue[p.type] = pps
          }
        }
      }
    }


    return {
      solution: {
        template,
        page,
        portals,
        selectIds,
        data: portalValue
      }
    }
  }


  async createTemplateView(tplData: any[]) {
    const stemp = getCurrentStimp();

    const [top] = tplData
    const shop_id = this.ctx.state.user.shop_id
    // 每次保存 新增一个版本
    const prevVresion = await this.ctx.model.PageVersion.findOne({
      where: {
        shop_id,
        page_id: top.pageId,
        template_id: top.templateId,
        status: 'draft',

      },
      order: [['id', 'DESC']],
      raw: true
    })

    const rs: Array<any> = []


    if (!prevVresion) {
      const versionId = await this.ctx.model.PageVersion.create({
        shop_id,
        page_id: top.pageId,
        template_id: top.templateId,
        version: 1,
        create_at: stemp,
        update_at: stemp,
        status: 'draft'
      })
      // console.log('xinz', versionId)
      // 新增一个版本
      for (const it of tplData) {
        const result = await this.ctx.model.AppUserPage.create({
          ...it,
          create_at: stemp,
          update_at: stemp,
          vId: versionId.id,
          shop_id
        })
        rs.push(result)
      }
      return rs
    } else {
      // 如果存在保本就更新
      for (const it of tplData) {
        const ps = await this.ctx.model.AppUserPage.findOne({
          where: {
            vId: prevVresion.id,
            portalId: it.portalId
          },
          raw: true
        })
        if (ps) {
          const result = await this.ctx.model.AppUserPage.update({
            properties: it.properties,
            // create_at: stemp,
            update_at: stemp,
            enabled: it.enabled,
            // vId: prevVresion.id,
            // shop_id
          }, {
            where: {
              shop_id,
              pageId: top.pageId,
              templateId: top.templateId,
              portalId: it.portalId,
              vId: prevVresion.id
            }
          })
          rs.push(result)
        } else {
          const result = await this.ctx.model.AppUserPage.create({
            ...it,
            create_at: stemp,
            update_at: stemp,
            vId: prevVresion.id,
            shop_id
          })
          rs.push(result)
        }
      }
    }



  }

  async publishTemplateView(tplId: number, pageId: number) {
    const shop_id = this.ctx.state.user.shop_id
    const prevVresion = await this.ctx.model.PageVersion.findOne({
      where: {
        shop_id,
        page_id: pageId,
        template_id: tplId,
        status: 'draft'
      },
      order: [['id', 'DESC']],
      raw: true
    })
    if (prevVresion) {
      await this.ctx.model.PageVersion.update({
        status: 'publish'
      }, {
        where: {
          id: prevVresion.id
        }
      })
 
      const rt = await this.ctx.model.AppUserPage.update({
        status: 'publish'
      }, {
        where: {
          pageId,
          templateId: tplId,
          shop_id,
          vId: prevVresion.id
        }
      })
      return rt
    }

  }

  async detailDev(tplId: number, pageId: number) {
    // const shop_id = this.ctx.state.user.shop_id
    // const stemp = getCurrentStimp();

    // const prevVresion = await this.ctx.model.PageVersion.findOne({
    //   where: {
    //     shop_id,
    //     page_id: pageId,
    //     template_id: tplId,
    //     status: 'draft'
    //   },
    //   order: [['id', 'DESC']],
    //   raw: true
    // })
    // let versionId

    // if (!prevVresion) {
    //   versionId = await this.ctx.model.PageVersion.create({
    //     shop_id,
    //     page_id: pageId,
    //     template_id: tplId,
    //     version: 1,
    //     create_at: stemp,
    //     update_at: stemp,
    //     status: 'draft'
    //   })
    // } else {
    //   versionId = prevVresion.id
    // }

    return await this.detail(tplId, pageId)
  }

  async detailPublic(tplId: number, pageId: number, shop_id: number) {
    // const shop_id = this.ctx.state.user.shop_id
    const prevVresion = await this.ctx.model.PageVersion.findOne({
      where: {
        shop_id,
        page_id: pageId,
        template_id: tplId,
        status: 'publish'
      },
      order: [['id', 'DESC']],
      raw: true
    })
    return await this.detail(tplId, pageId, 'publish', prevVresion.id)
  }

  // 获取抽奖配置信息
  async getLuckyData(shop_id: number) {
    return await this.ctx.model.LuckyDef.findOne({
      where: {
        shop_id
      },
      raw: true
    })
  }
}